var event = require('./event');

/**
 * <s>黑科技</s>全局操作回滚机制
 * 原理是其他模块有操作发生时, push进来一个自定义命令
 * 当需要回滚时, record pop一条命令, 通过event广播出去
 * 接受者自己进行解析, 做逆向操作
 */

var _inited = false;
var _max = 30;

var ret = {
	init: function () {
		if(_inited){
			return;
		}
		//TODO 加载操作历史
		this.undoList = [];
		this.todoList = [];

		_inited = true;
	},

	/**
	 *
	 * @param cmd {
	 * 		key:'note',
	 * 		param:{}
	 * }
	 */
	push: function(cmd){
		this.undoList.push(cmd);
		this.todoList = [];
		if(this.undoList.length > _max){
			this.undoList.shift();
		}
	},

    clearRedoList : function(){
        this.redoList = [];
    },

	redo: function(){
		if(!this.todoList.length){
			return;
		}
		var cmd = this.todoList.pop();
		this.undoList.push(cmd);
		event.trigger(event.events.global.redo, cmd);
	},

	undo: function(){
		if(!this.undoList.length){
			return;
		}
		var cmd = this.undoList.pop();
		this.todoList.push(cmd);  //加到队尾
		event.trigger(event.events.global.undo, cmd);
	}
};

module.exports = ret;